package chapter10.practice2;

/**
 * 类似于一个数组，用来储存
 * Created by yangliwei on 2017/10/19.
 */
public class Sequence {
    private Object[] items;
    private int next = 0;

    public Sequence(int size) {
        items = new Object[size];
    }

    //用来向数组里面添加数据
    public void add(Object obj) {
        if (next < items.length) {
            items[next++] = obj;
        }
    }

    //用来遍历Sequence里面的数据
    private class SequenceSelector implements Selector {
        //用来供selectot迭代使用，selector迭代最好不要使用外部的next，防止和add函数冲突
        int i = 0;

        @Override
        public void next() {
            if (i < items.length)
                i++;
        }

        @Override
        public Object current() {
            return items[i];
        }

        @Override
        public boolean hasNext() {
            return i < items.length;
        }
    }

    /**
     * 获取该序列的迭代器，使用了多态，使该序列可以用多种迭代器（Selector）
     *
     * @return
     */
    public Selector getSelector() {
        return new SequenceSelector();
    }

    public static void main(String[] args) {
        Sequence sequence = new Sequence(10);
        for (int i = 0; i < 10; i++) {
            sequence.add("hello " + i);
        }
        Selector selector = sequence.getSelector();
        while(selector.hasNext()){
            System.out.println(selector.current());
            selector.next();
        }
    }
}
